package cn.itsource.interceptor;

import cn.itsource.constant.SystemConstant;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果是前台系统的请求 - 直接放行
        String requestType = request.getHeader("requestType");
        if(requestType != null){
            return true;
        }

        HttpSession session = request.getSession();
        Object obj = session.getAttribute(SystemConstant.USER_IN_SESSION);
        if(obj == null){//没有登录 or 登录过期了
            //告诉前端，我给你响应一个json格式的数据，用的字符集是UTF-8
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print("{\"success\":false,\"message\":\"toLogin\"}");
            return false; //
        }
        return true;
    }
}
